/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.zprofilefrontend.model;

import com.vng.zing.logger.ZLogger;
import com.vng.zing.zprofile.thrift.wrapper.ZProfileClientInstance;
import com.vng.zing.zprofilefrontend.handlers.LogInHandler;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *
 * @author namhh
 */
public class CityModel {

    private Map<Short, String> cities = null;
    private static CityModel _instance;
    private static final org.apache.log4j.Logger _Logger = ZLogger.getLogger(LogInHandler.class);
    private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();
    private final ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(new Callable() {
        @Override
        public Object call() throws Exception {
            try {
                writeLock.lock();
                _instance = new CityModel();
                _Logger.info("Update city map");
            } finally {
                writeLock.unlock();
            }
            return null;
        }
    },
            300,
            TimeUnit.SECONDS);

    private CityModel() {
        cities = ZProfileClientInstance.getInstance().getClient().getAllCity();
    }

    public static synchronized CityModel getInstance() {
        return (_instance == null) ? _instance = new CityModel() : _instance;
    }

    public Map<Short, String> getAllCities() {
        try {
            readLock.lock();
            return cities;
        } finally {
            readLock.unlock();
        }
    }

    public String get(short key) {
        try {
            readLock.lock();
            return (String) cities.get(key);
        } finally {
            readLock.unlock();
        }
    }

}
